﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MDF.Cacher.Interfaces;
using System.Configuration;
using MDF.Cacher.Implements;

namespace MDF.Cacher.Managements
{
    public class CacheManager
    {
        private static ICache m_cache = null;
        private static string m_setting=null;
        private static int CachingDefaultTimeout = 10;
        private static object keylock=new object();
        private CacheManager()
        {
            Init();
        }
        public static ICache GetInstance()
        {
            Init();
            return m_cache;
        }
        private static void Init()
        {
            lock (keylock)
            {
                if (m_cache == null)
                {
                    if (m_setting == null)
                    {
                        m_setting = ConfigurationManager.AppSettings["CacheType"];
                        if (string.IsNullOrEmpty(m_setting))
                            m_setting = "Memory";
                        string strCachingDefaultTimeout = ConfigurationManager.AppSettings["CachingDefaultTimeout"];
                        if (!string.IsNullOrEmpty(strCachingDefaultTimeout))
                        {
                            Int32.TryParse(strCachingDefaultTimeout, out CachingDefaultTimeout);
                        }
                    }
                    switch (m_setting)
                    {
                        case "Memory":
                            m_cache = new MemoryCache(CachingDefaultTimeout);
                            break;
                        case "File":
                            m_cache = new FileCache();
                            break;
                        default:
                            m_cache = new MemoryCache();
                            break;
                    }
                }
            }
        }
    }
}
